package com.fcgzs.sellergoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fcgzs.entity.PageResult;
import com.fcgzs.sellergoods.dao.*;
import com.fcgzs.sellergoods.group.GoodsEntity;
import com.fcgzs.sellergoods.pojo.*;
import com.fcgzs.sellergoods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/****
 * @Author:ujiuye
 * @Description:Goods业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
@Transactional //开启事务管理
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {


    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsDescMapper goodsDescMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemCatMapper itemCatMapper;


    @Autowired
    private BrandMapper brandMapper;

    /**
     * Goods条件+分页查询
     *
     * @param goods 查询条件
     * @param page  页码
     * @param size  页大小
     * @return 分页结果
     */
    @Override
    public PageResult<Goods> findPage(Goods goods, int page, int size) {
        Page<Goods> mypage = new Page<>(page, size);
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        IPage<Goods> iPage = this.page(mypage, queryWrapper);
        return new PageResult<Goods>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * Goods分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult<Goods> findPage(int page, int size) {
        Page<Goods> mypage = new Page<>(page, size);
        IPage<Goods> iPage = this.page(mypage, new QueryWrapper<Goods>());

        return new PageResult<Goods>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * Goods条件查询
     *
     * @param goods
     * @return
     */
    @Override
    public List<Goods> findList(Goods goods) {
        //构建查询条件
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        //根据构建的条件查询数据
        return this.list(queryWrapper);
    }


    /**
     * Goods构建查询对象
     *
     * @param goods
     * @return
     */
    public QueryWrapper<Goods> createQueryWrapper(Goods goods) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (goods != null) {
            // 主键
            if (!StringUtils.isEmpty(goods.getId())) {
                queryWrapper.eq("id", goods.getId());
            }
            // 商家ID
            if (!StringUtils.isEmpty(goods.getSellerId())) {
                queryWrapper.eq("seller_id", goods.getSellerId());
            }
            // SPU名
            if (!StringUtils.isEmpty(goods.getGoodsName())) {
                queryWrapper.eq("goods_name", goods.getGoodsName());
            }
            // 默认SKU
            if (!StringUtils.isEmpty(goods.getDefaultItemId())) {
                queryWrapper.eq("default_item_id", goods.getDefaultItemId());
            }
            // 状态
            if (!StringUtils.isEmpty(goods.getAuditStatus())) {
                queryWrapper.eq("audit_status", goods.getAuditStatus());
            }
            // 是否上架
            if (!StringUtils.isEmpty(goods.getIsMarketable())) {
                queryWrapper.eq("is_marketable", goods.getIsMarketable());
            }
            // 品牌
            if (!StringUtils.isEmpty(goods.getBrandId())) {
                queryWrapper.eq("brand_id", goods.getBrandId());
            }
            // 副标题
            if (!StringUtils.isEmpty(goods.getCaption())) {
                queryWrapper.eq("caption", goods.getCaption());
            }
            // 一级类目
            if (!StringUtils.isEmpty(goods.getCategory1Id())) {
                queryWrapper.eq("category1_id", goods.getCategory1Id());
            }
            // 二级类目
            if (!StringUtils.isEmpty(goods.getCategory2Id())) {
                queryWrapper.eq("category2_id", goods.getCategory2Id());
            }
            // 三级类目
            if (!StringUtils.isEmpty(goods.getCategory3Id())) {
                queryWrapper.eq("category3_id", goods.getCategory3Id());
            }
            // 小图
            if (!StringUtils.isEmpty(goods.getSmallPic())) {
                queryWrapper.eq("small_pic", goods.getSmallPic());
            }
            // 商城价
            if (!StringUtils.isEmpty(goods.getPrice())) {
                queryWrapper.eq("price", goods.getPrice());
            }
            // 分类模板ID
            if (!StringUtils.isEmpty(goods.getTypeTemplateId())) {
                queryWrapper.eq("type_template_id", goods.getTypeTemplateId());
            }
            // 是否启用规格
            if (!StringUtils.isEmpty(goods.getIsEnableSpec())) {
                queryWrapper.eq("is_enable_spec", goods.getIsEnableSpec());
            }
            // 是否删除
            if (!StringUtils.isEmpty(goods.getIsDelete())) {
                queryWrapper.eq("is_delete", goods.getIsDelete());
            }
        }
        return queryWrapper;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        //1.根据ID查询商品信息
        Goods goods = goodsMapper.selectById(id);
        //2.判断审核状态，如果审核通过，则不能直接删除
        if ("1".equals(goods.getAuditStatus())) {
            throw new RuntimeException("商品已审核通过，不能删除");
        }
        //3.设置删除标识位
        goods.setIsDelete("1");
        //4.重置审核状态为未审核
        goods.setAuditStatus("0");   //未审核
        //5.执行修改
        goodsMapper.updateById(goods);
    }

    /**
     * 修改Goods
     *
     * @param goods
     */
    @Override
    public void update(GoodsEntity goodsEntity) {
        //1.将审核状态设置未审核
        goodsEntity.getGoods().setAuditStatus("0");   //未审核
        //2.修改SPU信息
        goodsMapper.updateById(goodsEntity.getGoods());
        //3.修改扩展信息
        goodsDescMapper.updateById(goodsEntity.getGoodsDesc());
        //4.根据SPU的ID删除原有SKU的数据
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsEntity.getGoods().getId());
        //执行删除
        itemMapper.delete(queryWrapper);
        //5.执行添加SKU数据
        this.createItem(goodsEntity);


    }

    /**
     * 增加Goods
     *
     * @param goods
     */
    @Override
    public void add(GoodsEntity goodsEntity) {
        //1.将审核状态设置为未审核
        goodsEntity.getGoods().setAuditStatus("0");    //未审核
        //2.保存SPU对象
        goodsMapper.insert(goodsEntity.getGoods());
        //3.得到SPU对象的ID
        //4.向扩展信息对象中设置主键
        goodsEntity.getGoodsDesc().setGoodsId(goodsEntity.getGoods().getId());
        //5.保存扩展信息对象
        goodsDescMapper.insert(goodsEntity.getGoodsDesc());

        int i = 10/0;

        this.createItem(goodsEntity);

    }

    private void setItemValue(GoodsEntity goodsEntity, Item item) {
        item.setCategoryId(goodsEntity.getGoods().getCategory3Id());     //分类ID 三级
        item.setCreateTime(new Date());                             //创建时间
        item.setUpdateTime(new Date());                             //更新时间
        item.setGoodsId(goodsEntity.getGoods().getId());                //SPU的ID
        //根据分类ID查询分类信息
        ItemCat itemCat = itemCatMapper.selectById(item.getCategoryId());
        item.setCategory(itemCat.getName());                        //分类信息
        //根据品牌ID查询品牌信息
        Brand brand = brandMapper.selectById(goodsEntity.getGoods().getBrandId());
        item.setBrand(brand.getName());                             //品牌信息
        //从扩展信息表中取得图片数据
        List<Map> imageList = JSON.parseArray(goodsEntity.getGoodsDesc().getItemImages(), Map.class);
        if (!CollectionUtils.isEmpty(imageList)) {
            String url = (String) imageList.get(0).get("url");
            item.setImage(url);             //图片信息
        }
    }

    private void createItem(GoodsEntity goodsEntity) {
        //判断是否启用规格
        if ("1".equals(goodsEntity.getGoods().getIsEnableSpec())) {


            //6.保存SKU对象
            if (!CollectionUtils.isEmpty(goodsEntity.getItemList())) {
                for (Item item : goodsEntity.getItemList()) {
                    //{"机身内存"：“16G”，“网络制式":"联通4G"}‘
                    Map<String, String> specMap = JSON.parseObject(item.getSpec(), Map.class);
                    String title = goodsEntity.getGoods().getGoodsName(); //产品标题
                    for (String key : specMap.keySet()) {
                        title += specMap.get(key) + " ";
                    }
                    item.setTitle(title);           //SKU标题
                    this.setItemValue(goodsEntity, item);
                    //执行保存SKU
                    itemMapper.insert(item);
                }
            }
        } else {
            Item item = new Item();
            item.setTitle(goodsEntity.getGoods().getGoodsName());
            item.setPrice(goodsEntity.getGoods().getPrice());
            item.setNum(9999);
            item.setStatus("1");
            item.setIsDefault("1");
            item.setSpec("{}");
            this.setItemValue(goodsEntity, item);
            //执行保存SKU
            itemMapper.insert(item);
        }
    }

    /**
     * 根据ID查询Goods
     *
     * @param id
     * @return
     */
    @Override
    public GoodsEntity findById(Long id) {
        //1.查询SPU信息
        Goods goods = goodsMapper.selectById(id);
        //2.查询扩展信息
        GoodsDesc goodsDesc = goodsDescMapper.selectById(id);
        //3.条件查询SKU信息
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", id);
        List<Item> itemList = itemMapper.selectList(queryWrapper);
        //4.设置到复合实体
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setGoods(goods);
        goodsEntity.setGoodsDesc(goodsDesc);
        goodsEntity.setItemList(itemList);
        return goodsEntity;
    }

    /**
     * 查询Goods全部数据
     *
     * @return
     */
    @Override
    public List<Goods> findAll() {
        return this.list(new QueryWrapper<Goods>());
    }

    /**
     * 审核商品
     *
     * @param id
     */
    @Override
    public void audit(Long id) {
        //1.根据ID查询商品信息
        Goods goods = goodsMapper.selectById(id);
        //判断删除状态
        if ("1".equals(goods.getIsDelete())) {
            throw new RuntimeException("该商品已删除，不能被审核");
        }
        //2.设置审核通过状态
        goods.setAuditStatus("1");   //审核通过
        goods.setIsMarketable("1");   //已上架
        //3.执行修改商品
        goodsMapper.updateById(goods);
    }
}
